#!/bin/bash

COMMAND=$1

PHP_VERSION=8.3
DB_VERSION=8
LARAVEL_VERSION=12.*
PHPUNIT_VERSION=10.*
DEPENDENCY_VERSIONS=prefer-stable

PHPUNIT_PREPEND=
PHPUNIT_APPEND=

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --php) PHP_VERSION="$2"; shift ;;
        --db) DB_VERSION="$2"; shift ;;
        --laravel) LARAVEL_VERSION="$2"; shift ;;
        --phpunit) PHPUNIT_VERSION="$2" PHPUNIT_APPEND="--configuration phpunit-$2.xml"; shift ;;
        --dependencies) DEPENDENCY_VERSIONS="$2"; shift ;;
        --coverage) PHPUNIT_APPEND="${PHPUNIT_APPEND} --coverage-clover=coverage.xml" PHPUNIT_PREPEND="${PHPUNIT_PREPEND} XDEBUG_MODE=coverage";;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

RUNCOMMAND="composer require 'laravel/framework:$LARAVEL_VERSION' --no-interaction --no-update"

# If LARAVEL_VERSION is 9.*, then we need to install doctrine/dbal 3.0^
if [[ $LARAVEL_VERSION == 9.* ]]; then
    RUNCOMMAND="${RUNCOMMAND} && composer require 'doctrine/dbal:^3.0' --no-interaction --no-update"
fi

RUNCOMMAND="${RUNCOMMAND} && composer require 'laravel/laravel:$LARAVEL_VERSION' --dev --no-interaction --no-update"
RUNCOMMAND="${RUNCOMMAND} && composer require 'phpunit/phpunit:$PHPUNIT_VERSION' --dev --no-interaction --no-update"
RUNCOMMAND="${RUNCOMMAND} && composer update --no-ansi --no-interaction --$DEPENDENCY_VERSIONS"
RUNCOMMAND="${RUNCOMMAND} && composer update --no-ansi --no-interaction nesbot/carbon"
RUNCOMMAND="${RUNCOMMAND} && /ops/wait-for-it.sh mysql:3306 --timeout=120"
RUNCOMMAND="${RUNCOMMAND} && $PHPUNIT_PREPEND vendor/bin/phpunit $PHPUNIT_APPEND"

echo "${RUNCOMMAND}"
echo "PHP_VERSION=$PHP_VERSION DB_VERSION=$DB_VERSION docker compose -f ./.dev/docker/docker-compose.yaml"
PHP_VERSION=$PHP_VERSION DB_VERSION=$DB_VERSION docker compose -f ./.dev/docker/docker-compose.yaml run -T --rm --service-ports --use-aliases php bash -c "${RUNCOMMAND}"
